﻿using ComponentFactory.Krypton.Toolkit;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using TfsHelper.Model;
using TfsHelper.Model.DTOs;

namespace TfsHelper.WinFrontEnd
{
    public partial class frmPostTimes : KryptonForm
    {
        #region " Fields "

        private int minutes = 0;
        private double round = 0;

        private List<DTOTime> colTimes = null;
        private List<DTOTime> colTimesDS = new List<DTOTime>();

        #endregion

        #region " Constructor "

        public frmPostTimes()
        {
            InitializeComponent();

            using (TfsModel model = new TfsModel())
            {
                colTimes = (from time in model.Time
                            where time.Start >= DateTime.Today && time.Start <= DateTime.Today.AddDays(1).AddSeconds(-1)
                            let fulltime = time.Finish.Value - time.Start.Value
                            select new DTOTime
                            {
                                WorkitemId = time.WorkitemId,
                                Time = fulltime,
                                TFSTime = 0
                            }).ToList();
            }
        }

        #endregion

        #region " Handlers "

        private void frmPostTimes_Load(object sender, EventArgs e)
        {

        }

        private void btnPost_Click(object sender, EventArgs e)
        {
            if (KryptonMessageBox.Show("Are you sure to post the selected workitem times to TFS?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                var wiStore = Program.tfsSrv.GetService<WorkItemStore>();
                foreach (DataGridViewRow row in gridWIs.Rows)
                {
                    if (row.Cells[0].Value != null)
                    {
                        if ((bool)(row.Cells[0].Value) == true)
                        {
                            var wi = wiStore.GetWorkItem((int)row.Cells[1].Value);
                            try
                            {
                                wi.Fields["Completed Work"].Value = (double)wi.Fields["Completed Work"].Value + (double)row.Cells[3].Value;
                                if (wi.IsValid())
                                {
                                    wi.Save(SaveFlags.MergeAll);
                                }
                                else
                                {
                                    KryptonMessageBox.Show("There was an error trying to save item " + wi.Id + ". Verify it has a correct amount of time.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                    return;
                                }
                            }
                            catch (Exception exc)
                            {
                                KryptonMessageBox.Show("There was an error trying to save item " + wi.Id + ".\n" + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return;
                            }
                        }
                    }
                }

                KryptonMessageBox.Show("All times were posted to TFS.", "Post to TFS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
            }
        }

        #endregion

        #region " Methods "

        public void LoadTimes(IList<Workitem> colWorkitems)
        {
            DTOTime time;
            TimeSpan sumTime = new TimeSpan();
            foreach (var wi in colWorkitems)
            {
                time = colTimes.FirstOrDefault(t => t.WorkitemId == wi.WorkitemId);
                if (time == null)
                {
                    colTimesDS.Add(new DTOTime
                    {
                        WorkitemId = wi.WorkitemId,
                        Time = new TimeSpan(),
                        TFSTime = 0
                    });
                }
                else
                {
                    sumTime = new TimeSpan(colTimes.Where(x => x.WorkitemId == wi.WorkitemId).Sum(t => t.Time.Ticks));
                    colTimesDS.Add(new DTOTime
                    {
                        WorkitemId = wi.WorkitemId,
                        Time = sumTime,
                        TFSTime = GetTfsTime(sumTime)
                    });
                }
            }

            gridWIs.DataSource = colTimesDS;
        }

        private double GetTfsTime(TimeSpan time)
        {
            minutes = time.Minutes;
            round = (double)minutes / 60 * 100;
            minutes = Convert.ToInt32(Math.Round(round / 25, MidpointRounding.ToEven) * 25);

            if (minutes == 100)
                return (time.Hours + 1);
            else
                return (time.Hours + (minutes / 100D));
        }

        #endregion
    }
}
